// packageF/tourAround/travelIndex/travelIndex.js
const app = getApp();
import tool from "../../../utils/util";
let location = require("../../../mybehaviors/location/location");
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
Page({
  behaviors: [skinBehavior,location],
  /**
   * 页面的初始数据
   */
  data: {
    active: 1,
    zIndex: 100,
    isBgFlag: false,
    addressOpen: false,
    pageOpen: false,
    makeOpen: false,
    subscribeFlag: false,
    subscribeText: '全部分类',
    addressValue: 0,
    presentTime: "",
    addressList: [],
    cityText: "全部区域",
    cityValue: "", //获取城市编码的
    addressCity: "", //显示站点的
    query: {
      //筛选商品的
      page: 1,
      longitude: "",
      latitude: "",
      city: "",
      travel_around_goods_type: 0,
      is_recommand: 0,
      category: 0,
      title: "",
      cityCode: "",
      basic_info:1
    },
    addIndex: -1,
    subscribeIndex: 0,
    pageScrollTopV:0,
    optionIndex: 1,
    container: null,
    indexBanner: [], //轮播图
    activityList: [], //分类
    classifyList: [], //分类
    rankingList: [],
    goodsList: [],
    locationStatus: false, //判断是否有传定位
    isLoadMore: true,
    total_page: 0,
    locationMore: true,
    //客服插件
    showKefu: false,
    customer_open: "",
    cservice: "",
    service_mobile: "",
    service_QRcode: '',
    //处理时间
    formatPoints: '',
    computingFlag: '',
    beforeTime: '',
    siteName:'', //商城名称
    imageUrl:'',
    localCity:'',
    Hei:"",          //这是swiper要动态设置的高度属性
    goodsFlag:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if ((options.city ?? "") !== "") {
      //获取站点的编码
      this.setData({
        cityValue: Number(options.cityCode),
        'query.cityCode': Number(options.cityCode),
        'query.city': options.city,
        addressCity: options.city,
        localCity: options.city
      })
      this.aroundLocation();
      this.getGoodsList();
    } 
    
    
    this.getKefu();
    this.travelIndexData();
  },
  travelIndexData() {
    let cityCode = '';
    let city = '';
    if(this.data.localCity) {
      city = this.data.localCity || '';
    } else {
      cityCode = this.data.query.cityCode || '';
    }
    //轮播图和分类信息
    let urlStr = app.getNetAddresss("plugin.travel-around.frontend.index.index");
    app._getNetWork({
      url: urlStr,
      data: {city:city,cityCode:cityCode,basic_info:1},
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          let activityList = res.data.category;
          let basicInfo =  res.basic_info;
          let classify = []
          if (activityList.length > 10) {
            //超过十个拆分数组换行显示
             classify = activityList.splice(10, activityList.length - 10);
          }
          this.setData({
            rankingList: res.data.goods,
            indexBanner: res.data.banner,
            activityList:activityList,
            classifyList: classify,
            siteName:basicInfo?.home?.mailInfo?.name,
            imageUrl:basicInfo?.home?.mailInfo?.logo_url,
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
        wx.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: this.data.themeBaseColor,
          animation: {
            duration: 400,
            timingFunc: 'easeIn'
          }
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  imgH(e){
    var winWid = wx.getSystemInfoSync().windowWidth;//获取当前屏幕的宽度
    var imgh=e.detail.height;//图片高度
    var imgw=e.detail.width;
    var swiperH=winWid*imgh/imgw + "px"　//等比设置swiper的高度。  即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度    ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
        Hei:swiperH//设置高度
    })
  },
  goTop(e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  showService() {
    this.setData({
      showKefu:true
    })
  },
  searchOn() {
    wx.navigateTo({
      url: `/packageF/tourAround/tourSearch/tourSearch?keyWord=${this.data.query.title}&city=${this.data.localCity}&latitude=${this.data.query.latitude}&longitude=${this.data.query.longitude}&cityCode=${this.data.query.cityCode}`,
    })
  },
  rankingOn(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/packageF/tourAround/tourAroundGoodsDetails/tourAroundGoodsDetails?goodsId=${id}&latitude=${this.data.query.latitude}&longitude=${this.data.query.longitude}`,
    })
  },
  subscribeOn(event) {
    let index = event.currentTarget.dataset.index;
    let subscribeFlag = false;
    //筛选信息
    if (index === 3) {
      // this.makeOpen = !this.makeOpen;
      this.setData({
        makeOpen: true,
        pageOpen: !this.data.pageOpen,
        // subscribeFlag:!this.data.subscribeFlag
      })
      
      if (this.data.isBgFlag) { //吸顶不吸顶的判断是否显示背景色
        subscribeFlag= true;
      } else { 
        subscribeFlag = false;
        if (this.data.addressOpen || this.data.makeOpen) { //存在打开弹窗就隐藏
          subscribeFlag = true;
        } else {
          subscribeFlag = false;
        }
      }
      
      this.setData({
        subscribeFlag:subscribeFlag
      })
      if (!this.data.isBgFlag) { 
        this.setData({
          isBgFlag: !this.data.isBgFlag
        })
      }
      this.createSelectorQuery().select('#subscribes').boundingClientRect(res => {
        // 到这里，我们可以从res中读到id为container的top，即离顶部的距离（px）
        // 2使用wx.pageScrollTo()将页面滚动到对应位置
        // console.log(res.top,this.data.pageScrollTopV,res.top + this.data.pageScrollTopV)
        if(res.top>0){
          wx.pageScrollTo({
            scrollTop: res.top + this.data.pageScrollTopV, // 滚动到的位置（距离顶部 px）
            duration: 0 //滚动所需时间 如果不需要滚动过渡动画，设为0（ms）
          })
          this.setData({
            isBgFlag:true
          })
        }
      }).exec()
    } else if (index === 1) {
      if (this.data.isBgFlag) {
        subscribeFlag = true;
      } else { 
        subscribeFlag = false;
      }
      this.setData({
        makeOpen: false,
        addressOpen: false,
        pageOpen: false,
        subscribeFlag:subscribeFlag,
        'query.is_recommand': 1,
        'query.page': 1,
      })
      this.getGoodsList();
      if(this.data.subscribeFlag) {
        this.goTop();
      }
    } else {
      if (this.data.isBgFlag) {
        subscribeFlag = true;
      } else { 
        subscribeFlag = false;
      }
      this.setData({
        makeOpen: false,
        addressOpen: false,
        subscribeFlag:subscribeFlag,
        pageOpen: false,
        'query.page': 1,
      })
      try {
        this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
  
          let adcode = mapdata.ad_info.adcode;
          let interceptionCity = adcode.toString().slice(0, 4) + "00";
          this.setData({
            'query.latitude': e.lat,
            'query.longitude': e.lng,
            cityValue: interceptionCity,
          });
          this.getGoodsList();
        });
      } catch (e) {
        console.log(e);
        this.getGoodsList();
      }
      if(this.data.subscribeFlag) {
        this.goTop();
      }
    }
    this.setData({
      subscribeIndex: index
    })

  },
  onPageScroll: tool.throttle(function (msg) { // 获取滚动条当前位置
    let event = msg[0];
    this.setData({
      pageScrollTopV:event.scrollTop
    })
    if(event.scrollTop >= 1) {
      this.setData({
        isBgFlag: true,
      })
      
    } else {
      this.setData({
        isBgFlag: false,
      })
     
    }
  },50),
  maskOn() {
    //开启蒙版遮挡
    this.setData({
      makeOpen: false,
      addressOpen: false,
      pageOpen:false,
    })
  },
  // 获取客服
  getKefu() {
    let goods_id = "";
    let urlStr = app.getNetAddresss("goods.customer-service.index");
    app._postNetWork({
      url: urlStr,
      data: {
        goods_id: goods_id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            customer_open:res.data.customer_open == 0?false:true,
            showKefu: false,
            cservice: res.data.cservice,
            service_QRcode: res.data.service_QRcode,
            service_mobile: res.data.service_mobile,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  swiperNav(nav) {
    wx.navigateTo({
      url: nav,
    })
  },
  cityNavOn() {
    wx.navigateTo({
      url: `/packageF/tourAround/tourCityList/tourCityList?cityCode=${this.data.cityValue}&localCity=${this.data.addressCity}`,
    });
  },
  commodityNav(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageF/tourAround/tourAroundGoodsDetails/tourAroundGoodsDetails?goodsId=' + id,
    });
  },
  rankingNav() {
    wx.navigateTo({
      url: `/packageF/tourAround/rankingList/rankingList?cityCode=${this.data.cityValue}&city=${this.data.localCity}`
    });
  },
  subscribeOption(event) {
    let {index,name} = event.currentTarget.dataset;
    //选择评价的
    this.setData({
      optionIndex: index,
      subscribeText: name,
      makeOpen: false,
      addressOpen: false,
      pageOpen: false,
      'query.travel_around_goods_type': index,
      'query.page': 1
    })
    if(this.data.subscribeFlag) {
      this.goTop();
    }
    this.getGoodsList();
  },
  aroundLocation() {
    let urlStr = app.getNetAddresss("plugin.travel-around.frontend.index.index.getTravelAroundLocation");
    let json = {
      cityCode: this.data.cityValue,
      city: this.data.city
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          this.setData({
            addressList: res.data.matching || []
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  toAddress(event) {
    let {index, city} = event.currentTarget.dataset;
    this.setData({
      addIndex: index,
      cityText: city,
      'query.city': city,
      addressOpen: false,
      pageOpen: false
    })
    if(this.data.subscribeFlag) {
      this.goTop();
    }
    this.getGoodsList();
    
  },
  allArea() {
    this.setData({
      addIndex: -1,
      cityText: '全部区域',
      addressOpen: false
    })
  },
  getGoodsList() {
    if (this.data.query.latitude === "" && this.data.query.longitude === "") {
      this.setData({
        locationMore: false,
      })
    } else {
      this.setData({
        locationMore: true,
      })
    }
    this.setData({
      goodsFlag:false
    })
    let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.goods.getGoodsList");
    app._postNetWork({
      url: urlStr,
      data:this.data.query,
      success:  (resdata) => {
        let res = resdata.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          this.data.totalPage = res.data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          this.setData({
            goodsList: res.data.data,
            goodsFlag:true
          })
        } else {
          this.data.page = this.data.page - 1;
          this.isLoadMore = false;
          this.goodsFlag = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  addMenuOpen() {
    this.setData({
      addressOpen: true,
      pageOpen: !this.data.pageOpen,
      makeOpen:false,
      subscribeIndex:4
    });
    let subscribeFlag = false;
    if (this.data.isBgFlag) { //吸顶不吸顶的判断是否显示背景色
      subscribeFlag = true;
    } else { 
      subscribeFlag = false;
    }
    if (this.data.addressOpen) { 
      subscribeFlag = true;
    }
    this.setData({
      subscribeFlag:subscribeFlag
    });
    if (!this.data.isBgFlag) {
      this.setData({
        isBgFlag:!this.data.isBgFlag
      });
    }
    
    this.createSelectorQuery().select('#selectAddress').boundingClientRect(res => {
      // 到这里，我们可以从res中读到id为container的top，即离顶部的距离（px）
      // 2使用wx.pageScrollTo()将页面滚动到对应位置
      if(res.top>0){
        wx.pageScrollTo({
          scrollTop: res.top + this.data.pageScrollTopV, // 滚动到的位置（距离顶部 px）
          duration: 0 //滚动所需时间 如果不需要滚动过渡动画，设为0（ms）
        })
      }
    }).exec()
  },
  classifyOn(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageF/tourAround/categories/categories?childrenId=' + id +`&cityCode=${this.data.cityValue}&city=${this.data.query.city}&latitude=${this.data.query.latitude}&longitude=${this.data.query.longitude}`,
    })
  },
  subscribeSticky: tool.throttle(function(msg) {
    let event = msg[0];
    let scrollTop = event.detail.isFixed;
    if(typeof(scrollTop) === "undefined") return; //默认是undefined
    if(scrollTop) {
        this.setData({
          subscribeFlag: true
        })
      
    } else {
      this.setData({
        subscribeFlag: false
      })
      if(this.data.addressOpen || this.data.makeOpen) {
        this.setData({
          subscribeFlag:true
        });
      }
    }
  }),
  getGood() {
    let urlStr = app.getNetAddresss("goods.customer-service.index");
    let json = {
      goods_id: ""
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          this.setData({
            serviceQRcode: res.data.service_QRcode,
            serviceMobile: res.data.service_mobile,
            cservice: res.data.cservice
          })
          
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },
  //获取更多数据
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.query.page >= this.data.totalPage) {
      return;
    } else {
      this.data.query.page = this.data.query.page + 1;
      let urlStr = app.getNetAddresss("plugin.travel-around.frontend.goods.goods.getGoodsList");
      app._getNetWork({
        url: urlStr,
        data: this.data.query,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              goodsList : this.data.goodsList.concat(list),
            })
          } else {
            this.data.query.page = this.data.query.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      container: () => wx.createSelectorQuery().select('#travelIndex'),
      presentTime:new Date().getTime()
    });
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        let adcode = mapdata.ad_info.adcode;
        let interceptionCity = adcode.toString().slice(0, 4) + "00";
        let addressCity = '';
        this.setData({
          'query.latitude': e.lat,
          'query.longitude': e.lng,
          'query.cityCode': interceptionCity,
          cityValue: interceptionCity
        });
        if(this.data.addressCity === '') {
          this.setData({
          addressCity : mapdata.ad_info.city

          })
        }
        
        this.travelIndexData();
        this.aroundLocation();
        this.getGoodsList();
        
      });
    } catch (e) {
      this.travelIndexData();
      this.aroundLocation();
      this.getGoodsList();
      console.log(e);
    }
    
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '周边游-' + this.data.siteName,
      imageUrl:this.data.imageUrl,
      path: `/packageF/tourAround/travelIndex/travelIndex?city=${this.data.query.city}&cityCode=${this.data.query.cityCode}&localCity=${this.data.localCity}&longitude=${this.data.query.longitude}&latitude=${this.data.query.latitude}`
    };
  },
  onShareTimeline() {
    return {
      title: '周边游-' + this.data.siteName,
      imageUrl:this.data.imageUrl,
      path: `/packageF/tourAround/travelIndex/travelIndex?city=${this.data.query.city}&cityCode=${this.data.query.cityCode}&localCity=${this.data.localCity}&longitude=${this.data.query.longitude}&latitude=${this.data.query.latitude}`
    };
  }
})